package com.controller;

import com.model.FlightModel;
import com.services.impl.FlightServicesImpl;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Program: exam
 * @ClassName: FlightSearchServletController
 * @Description: 航班模糊查询
 * @Author: li
 * @Create: 2024-12-23 14:17
 */
@WebServlet("/FlightSearchServlet")
public class FlightSearchServletController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        Map<String, Object> result = new HashMap<>();
        
        try {
            String cname = request.getParameter("fname");
            System.out.println("搜索参数 cname: " + cname); // 调试日志
            
            // 调用服务查询航班 - 只查询状态为1(可租用)的航班
            List<FlightModel> flightModels = new FlightServicesImpl().fuzzyQueryByFlight(cname);
            System.out.println("查询到的航班数量: " + flightModels.size()); // 调试日志
            
            // 过滤掉已下架的航班


            // 处理图片路径
            for (FlightModel flightModel : flightModels) {
                String cimg = flightModel.getFimg();
                if (cimg != null && !cimg.isEmpty()) {
                    // 统一路径格式
                    if (!cimg.startsWith("/")) {
                        flightModel.setFimg("/upload/" + cimg);
                    }
                }
                System.out.println("航班信息: " + flightModel.getFname() + ", 图片路径: " + flightModel.getFimg());
            }
            
            // 返回结果
            result.put("code", 0);
            result.put("msg", "success");
            result.put("data", flightModels);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "查询航班失败：" + e.getMessage());
        }
        
        String jsonResult = JSONObject.fromObject(result).toString();
        System.out.println("返回结果: " + jsonResult); // 调试日志
        response.getWriter().write(jsonResult);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
}
